package com.example.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.service.AuthService;
import com.example.entity.User;
import com.example.common.Result;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.Map;
import java.util.HashMap;

@RestController
@RequestMapping("/api/auth")
public class AuthController {
    @Autowired
    private AuthService authService;

    @PostMapping("/login")
    public Result login(@RequestBody Map<String, String> credentials) {
        try {
            if (credentials == null) {
                return Result.error("登录信息不能为空");
            }
            
            String phone = credentials.get("phone");
            String password = credentials.get("password");
            
            if (phone == null || phone.trim().isEmpty()) {
                return Result.error("手机号不能为空");
            }
            if (password == null || password.trim().isEmpty()) {
                return Result.error("密码不能为空");
            }
            
            if (authService.authenticate(phone, password)) {
                // 获取用户信息
                User user = authService.getUserByPhone(phone);
                Map<String, Object> userData = new HashMap<>();
                userData.put("id", user.getId());
                userData.put("username", user.getUsername());
                userData.put("phone", user.getPhone());
                
                return Result.success(userData);
            } else {
                return Result.error("手机号或密码错误");
            }
        } catch (Exception e) {
            return Result.error("登录失败: " + e.getMessage());
        }
    }
}